package com.icez.calendar_view

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.util.Log
import android.widget.LinearLayout
import androidx.viewpager2.widget.ViewPager2

/**
 * 日历控件
 * @sample
 * @author Icez
 */
class CalendarView @JvmOverloads constructor(
    context: Context, val attrs: AttributeSet? = null
) : LinearLayout(context, attrs) {


    private var mViewPager2: ViewPager2? = null

    private var mCalendarPagerAdapter: CalendarPagerAdapter? = null


    // 日历的文字大小
    private var mDayTextSize: Float = 0f

    // 文字颜色
    private var mDayTextColor: Int = 0

    // 文字是否加粗
    private var mDayTextIsBold: Boolean = true

    // 文字控件的高度
    private var mDayTextHeight: Int = 0

    // 文字上下补丁
    private var mDayTextPaddingTopBottom: Int = 0

    // 范围颜色
    private var mDayRangeColor: Int = 0

    private var mMinYear: Int = Utils.currentYear() - 1

    private var mMaxYear: Int = mMinYear + 2

    var mCalendarViewConfig: CalendarViewConfig? = null

    // 文字点的大小
    private var mDayPointWidthHeight:Float = 0f

    //最大范围天数
    private var mMaxRangeDayNum: Int = 10
    // 是否开启范围选项
    private var mIsOpenRange: Boolean = true
    // 是否限制只能向未来日期进行选
    private var mIsLmitRangeNext: Boolean = true
    //是否限制开始范围必须是当前日期
    private var mIsLmitStartRangeCurrentDate: Boolean = true

    private var mRangeCorner:Float = 10f

    var mOnDayItemClickListener:OnDayItemClickListener ?= null
        set(value) {
            field = value
            mCalendarPagerAdapter?.mOnDayItemClickListener = field
        }

    var mOnDayRangeListener:OnDayRangeListener ?= null
        set(value) {
            field = value
            mCalendarPagerAdapter?.mOnDayRangeListener = field
        }

    private val mCalendarModels = ArrayList<CalendarModel>()
    
    private var mOnCurrentPageListener:OnCurrentPageListener ?= null


    private var mOnPageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            super.onPageSelected(position)
            Log.e("icez","切换执行: ${mCalendarModels[position].year} - ${mCalendarModels[position].month}")
            mCalendarPagerAdapter?.notifyItemChanged(position)
            mOnCurrentPageListener?.currentPage(mCalendarModels[position].year.toInt(),mCalendarModels[position].month.toInt())
        }
    }

    init {
        initValue()
        mViewPager2 = ViewPager2(context)

        for (y in mMinYear until (mMaxYear + 1)) {
            for (m in 1 until 13) {
                val mMonthDayModels = ArrayList<CalendarModel.MonthDayModel>()
                val weekDay = Utils.getDayForWeek(y, m, 1)
                val monthDays = Utils.getDayForMonth(y, m)
                val redundantDays = ArrayList<CalendarModel.MonthDayModel>()

                if (weekDay > 0) {
                    var preY = 0
                    var preM = 0
                    if (m == 1) {
                        preM = 12
                        preY = y - 1
                    } else {
                        preM = m - 1
                        preY = y
                    }
                    val preMonthDays = Utils.getDayForMonth(preY, preM)

                    for (d in (preMonthDays - weekDay + 1) until preMonthDays + 1) {
                        redundantDays.add(CalendarModel.MonthDayModel(""))
                    }
                }

                mMonthDayModels.addAll(redundantDays)

                for (d in 1 until (monthDays + 1)) {
                    mMonthDayModels.add(CalendarModel.MonthDayModel(d.toString()))
                }

                mCalendarModels.add(CalendarModel(y.toString(), m.toString(), mMonthDayModels))
            }
        }
        mCalendarPagerAdapter = mCalendarViewConfig?.let {
            CalendarPagerAdapter(R.layout.item_calendar_pager, mCalendarModels,
                it
            )
        }
        mViewPager2?.adapter = mCalendarPagerAdapter
        mViewPager2?.registerOnPageChangeCallback(mOnPageChangeCallback)
        mViewPager2?.setCurrentItem(
            (Utils.currentYear() - mMinYear) * 12 + Utils.currentMonth() - 1,
            false
        )
        addView(mViewPager2)
    }

    private fun initValue() {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.CalendarView)
        mDayTextSize = typedArray.getDimensionPixelSize(R.styleable.CalendarView_dayTextSize, 20).toFloat()
        mDayTextColor = typedArray.getColor(R.styleable.CalendarView_dayTextColor, Color.BLACK)
        mDayTextIsBold = typedArray.getBoolean(R.styleable.CalendarView_dayTextIsBold, true)
        mDayTextHeight =
            typedArray.getDimensionPixelOffset(R.styleable.CalendarView_dayTextHeight, 0)
        mDayTextPaddingTopBottom =
            typedArray.getDimensionPixelOffset(R.styleable.CalendarView_dayTextPaddingTopBottom, 10)
        mDayRangeColor = typedArray.getColor(R.styleable.CalendarView_dayRangeColor, Color.RED)
        mDayPointWidthHeight = typedArray.getDimensionPixelSize(R.styleable.CalendarView_dayPointWidthHeight,10).toFloat()
        mMaxRangeDayNum = typedArray.getInteger(R.styleable.CalendarView_maxRangeDayNum,10)
        mIsOpenRange = typedArray.getBoolean(R.styleable.CalendarView_isOpenRange,true)
        mIsLmitRangeNext = typedArray.getBoolean(R.styleable.CalendarView_isLmitRangeNext,true)
        mIsLmitStartRangeCurrentDate = typedArray.getBoolean(R.styleable.CalendarView_isLmitStartRangeCurrentDate,true)
        mRangeCorner = typedArray.getDimensionPixelSize(R.styleable.CalendarView_rangeCorner,10).toFloat()
        typedArray.recycle()

        mCalendarViewConfig = CalendarViewConfig(
            mDayTextColor = mDayTextColor,
            mDayRangeColor = mDayRangeColor,
            mDayTextHeight = mDayTextHeight,
            mDayTextIsBold = mDayTextIsBold,
            mDayTextPaddingTopBottom = mDayTextPaddingTopBottom,
            mDayTextSize = mDayTextSize,
            mDayPointWidthHeight = mDayPointWidthHeight,
            mMaxRangeDayNum = mMaxRangeDayNum,
            mIsOpenRange = mIsOpenRange,
            mIsLmitRangeNext = mIsLmitRangeNext,
            mIsLmitStartRangeCurrentDate = mIsLmitStartRangeCurrentDate,
            mRangeCorner = mRangeCorner
        )

    }
    
    
    /**
     * 获取当前页的年份
     * @sample 
     * @author Icez
     */
    fun getCurrentPageYear(): Int {
        return mCalendarModels[mViewPager2?.currentItem?:0].year.toInt()
    }
    
    /**
     * 获取当前页的月份
     * @sample 
     * @author Icez
     */
    fun getCurrentPageMonth():Int{
        return mCalendarModels[mViewPager2?.currentItem?:0].year.toInt()
    }

    /**
     * 刷新当前UI
     * @sample
     * @author Icez
     */
    fun refreshCurrentUI() {
        mCalendarPagerAdapter?.notifyItemChanged(mViewPager2?.currentItem ?: 0)
    }

    interface OnDayItemClickListener{
        fun dayItemClick(year:Int,month:Int,day:Int)
    }

    interface OnDayRangeListener{
        fun dayRange(starRangeDate:Long,endRangeDate:Long)
    }
    
    interface OnCurrentPageListener{
        fun currentPage(year:Int,month:Int)
    }

}